-- 更新地图中的内容

function builder:gen_xRect()
    local output = Root .. '\\maps\\' .. self.map
    --解析rect
    local path_w3r = output .. '\\map\\war3map.w3r'
    local rectParse = require 'module.rectParser'
    local rects = rectParse( path_w3r )
    local w3r = io.open( output .. '\\scripts\\xRect.lua' , 'w+' )
    if not w3r then
        print( 'xRect解析失败,无法获得地图里预设区域' )
        return
    end
    local lua = {}
    table_insert(lua, '--雪月框架 - xRect 预处理文件\n--该文件只读勿在此文件内写入代码\n\nlocal rct\n\n')
    local count = 0
    for index, rect in ipairs(rects) do
        --rect
        table_insert(lua, ("rct = rect:rect( %f, %f, %f, %f )\n"):format(
            rect.LB[1], rect.LB[2],
            rect.RT[1], rect.RT[2]
        )  )
        table_insert(lua, ("rct.weather = {base.sid(%d)}\n"):format(
            rect.weather
        )  )
        --xRect
        table_insert(lua, ('xrect._names[%d] = "%s"\n'):format(
            index,
            rect.name
        )  )
        table_insert(lua, ('xrect._n2o[%d] = rct\n\n'):format(
            index
        )  )
        count = count + 1
    end
    table_insert(lua, ('xrect._names[0] = (xrect._names[0] or 0) + %d\n'):format(
            count
        )  )
    table_insert(lua, ('xrect._n2o[0] = (xrect._n2o[0] or 0) + %d\n'):format(
        count
    )  )
    table_insert(lua, '\n')
    w3r:write(table.concat(lua))
    w3r:close()
end

function builder:unpackW3x()
    local terrain_w3x =  'Terrain.w3x'
    local input =  Root .. '\\maps\\' .. self.map .. '\\' .. terrain_w3x
    local output = Root .. '\\maps\\' .. self.map

    --删除原有缓存
    rd( output .. '\\map')
    rd( output .. '\\w3x2lni')
    rd( output .. '\\table')
    rd( output .. '\\map')
    rd( output .. '\\resource')
    rd( output .. '\\sound')

    local command = table.concat({
        "w3x2lni\\w2l.exe",
        'lni',
        '"'..input..'"',
        '"'..output..'"',
        '2>nul',
    },' ')
    mkdir( output ) --创建输出目录

    print("  >开始解包地形图")
    local file = io.popen(command:u2a(), "r")
    _print('', file:read("*a") ) --显示解包进度
    file:close()

    --解包完成

    self:gen_xRect()
end

function builder:updateTerrainFormW3x()
    local file = io.popen("certutil -hashfile " .. self.path_map:u2a() .. "\\Terrain.w3x MD5 2>nul", "r")
    local str = file:read "*a"
    file:close()
    
    local newCheckValue = str:match(":\n(%w+)\n")  -- 得到MD5 进行比对
    if not newCheckValue then
        newCheckValue = ''
        print("[1]项目目录下的地形图文件:Terrain.w3x 不存在 跳过地形图更新...")
        return
    end

    local oldCheckValue = self.mapcfg._ini.w3x.CheckValue or '0'
    print('MD5比对:', oldCheckValue, '=>', newCheckValue)
    if newCheckValue == oldCheckValue then
        print("[1]地形图未发生保存操作 跳过地形更新...")
        return
    end

    self.mapcfg._ini.w3x.CheckValue = newCheckValue
    self.mapcfg:save()

    print("[1]检测到地形图重新保存...")
    self:unpackW3x()

end
